<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRoleById,deleteRole,getRolePage, getRoleAuth,saveRoleAuth, updateRole, saveRole } from '@/api/role'
import { EditPen, Delete, Avatar } from '@element-plus/icons-vue'

// 添加导入获取所有权限的API
import { queryAllAuth } from '@/api/auth'

const allAuthList = ref([]);
const currentRoleId = ref('');

// 修改权限相关
const authDialogTitle = ref('修改权限');
const authDialogVisible = ref(false);

const roleList = ref([])

const role = ref({
  id: '',
  roleName: '',
  description: '',
  enabled: ''
})

const roleFormRef = ref()
const dialogTitle = ref('')
const dialogVisible = ref(false)
const isEditMode = ref(false)
const pageNo = ref(1)
const pageSize = ref(10)
const background = ref(true)
const total = ref(0)

const authListWithStatus = ref([]);

onMounted(() => {
  search();
  queryAuth();
})

const queryAuth = async () => {
  try {
    // 获取所有权限列表
    const result = await queryAllAuth(1, 100); // 获取前100个权限
    if (result.data.code == 200) {
      allAuthList.value = result.data.data.records || result.data.data || [];
    }
  } catch (error) {
    console.error('获取权限列表失败:', error);
  }
};

const search = async () => {
  try {
    const result = await getRolePage(pageNo.value, pageSize.value);
    
    if (result.data.code == 200) {
      roleList.value = result.data.data.records;
      total.value = result.data.data.total;
    } else {
      ElMessage.error('数据加载失败');
    }
  } catch (error) {
    ElMessage.error('网络请求失败');
  } 
};

const save = async () => { 
  if (!roleFormRef.value) return;
  roleFormRef.value.validate(async (valid) => { 
    if(valid){
      let result;
      // 使用isEditMode变量来判断是新增还是编辑
      if(isEditMode.value)//修改
       { 
        result = await updateRole(role.value)
      }
      else//新增
      {
          result = await saveRole(role.value)
      }
      if (result.data.code ==200) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        search()
      } else {
        ElMessage.error(result.msg)
      }
    }
    else {
      ElMessage.error('数据校验失败')
    }
  })
}

const addRole = () => { 
  dialogVisible.value = true;
  isEditMode.value = false
  dialogTitle.value = '新增角色信息'
  role.value = {
    id: '',
    roleName: '',
    description: '',
    enabled: true
  }
}

const handleSizeChange = (val) => {
  // 添加边界校验
  if (val < 1) val = 1;
  pageSize.value = val;
  pageNo.value = 1; // 重置到第一页
  search();
};

const handleCurrentChange = (val) => {
  // 添加边界校验
  if (val < 1) val = 1;
  if (val > Math.ceil(total.value / pageSize.value)) {
    val = Math.ceil(total.value / pageSize.value);
  }
  pageNo.value = val;
  search();
};

const rules = ref({
  id: [
    { required: true, message: '角色ID不能为空', trigger: 'blur' },
    { pattern: /^\d+$/, message: '角色ID必须为数字', trigger: 'blur' }
  ],
  roleName: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度在2-20个字符', trigger: 'blur' }
  ],
  description: [
    { max: 50, message: '描述不能超过50个字符', trigger: 'blur' }
  ],
})

const edit = async (id) => { 
  try {
    const result = await getRoleById(id)
    if (result.data.code ==200) {  
      dialogVisible.value = true
      isEditMode.value = true
      dialogTitle.value = '修改角色信息'
      // 将返回的数据赋值给user对象
      role.value = result.data.data
    } else {
      ElMessage.error('获取用户信息失败：' + (result.data.message || '未知错误'))
    }
  } catch (error) {
    ElMessage.error('请求失败：' + error.message)
  }
};

const deleteById = async (id) => { 
  ElMessageBox.confirm(
    '你确认删除该角色吗',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const result = await deleteRole(id)
        if (result.code) {
          ElMessage.success('删除成功')
          search()
        } else {
          ElMessage.error('删除失败')
        }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '您已取消删除',
      })
    })
};

// 修改权限功能
const editAuth = async (roleId) => {
  currentRoleId.value = roleId;
  authDialogTitle.value = '修改权限';
  
  try {
    // 获取所有权限列表
    if (allAuthList.value.length === 0) {
      await queryAuth();
    }
    
    // 获取角色当前拥有的权限
    const result = await getRoleAuth(roleId);
    if (result.data.code == 200) {
      // 根据API返回的数据结构正确处理权限
      const roleAuths = result.data.data || [];
      
      // 创建一个Map以便快速查找角色拥有的权限ID及状态
      const roleAuthMap = new Map();
      roleAuths.forEach(item => {
        if (item.auth && item.auth.id) {
          // 使用API返回的have字段值
          roleAuthMap.set(item.auth.id, item.have);
        }
      });
      
      // 映射所有权限并设置have属性
      authListWithStatus.value = allAuthList.value.map(auth => {
        const haveStatus = roleAuthMap.has(auth.id) ? roleAuthMap.get(auth.id) : false;
        return {
          ...auth,
          have: haveStatus
        };
      });
      
      authDialogVisible.value = true;
    } else {
      ElMessage.error('获取角色权限失败：' + (result.data.message || '未知错误'));
    }
  } catch (error) {
    ElMessage.error('请求失败：' + error.message);
  }
};

const saveAuth = async () => {
  try {
    // 构造请求数据
    const requestData = {
      roleId: currentRoleId.value,
      authIds: authListWithStatus.value
        .filter(auth => auth.have) // 只发送选中的权限
        .map(auth => (auth.id))
    };
    
    // 发送请求更新角色权限
    const result = await saveRoleAuth(requestData);
    console.log(requestData);
    console.log(result);
    if (result.data.code == 200) {
      ElMessage.success('权限更新成功');
      authDialogVisible.value = false;
      // 重新加载角色列表以更新权限信息
      search();
    } else {
      ElMessage.error('权限更新失败：' + (result.data.message || '未知错误'));
    }
  } catch (error) {
    ElMessage.error('权限更新失败：' + error.message);
  }
};

// 添加一个方法用于重置权限状态
const resetAuthStatus = () => {
  authListWithStatus.value = [];
  currentRoleId.value = '';
}
</script>

<template>
    <!-- 顶部标题 -->
    <div>
      <div id="title">角色管理</div><br>
    </div>

    <!-- 功能按钮 -->
    <el-button type="success" @click="addRole()">+ 新增角色信息</el-button>
    <br><br>
    <el-table :data="roleList" border style="width: 100%" >
      <el-table-column prop="id" label="角色id" align="center" width="200px" />
      <el-table-column prop="roleName" label="角色名称" align="center" width="200px" />
      <el-table-column prop="description" label="描述" align="center" width="200px" />
          <el-table-column label="状态" width="120" align="center">
  <template #default="scope">
    <el-button v-if="scope.row.enabled" type="success" plain>启用中</el-button>
    <el-button v-else type="danger" plain>禁用中</el-button>
  </template>
    </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="edit(scope.row.id)"><el-icon><EditPen /></el-icon>编辑</el-button>
          <el-button type="danger" size="small" @click="deleteById(scope.row.id)"><el-icon><Delete /></el-icon>删除</el-button>
          <el-button type="success" size="small" @click="editAuth(scope.row.id)"><el-icon><Avatar /></el-icon>查看权限</el-button>
        </template>
      </el-table-column>
    </el-table>

<br>
<br>
  <div class="container">
      <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 50]"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    </div>


      <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form :model="role" label-width="80px" :rules="rules" ref="roleFormRef" >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="角色id" prop="id">
            <el-input v-model="role.id" placeholder="请输入角色id" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="role.roleName" placeholder="请输入角色名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="描述" prop="description">
            <el-input v-model="role.description" placeholder="请输入描述" />
          </el-form-item></el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="enabled">
            <el-radio-group v-model="role.enabled" >
              <el-radio :label="true">启用</el-radio>
              <el-radio :label="false">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>


    <el-form-item>
      <el-button type="success" @click="save()">确认</el-button>
      <el-button type="primary" @click="dialogVisible = false">取消</el-button>
    </el-form-item>
  </el-form>
  </el-dialog>

  <el-dialog v-model="authDialogVisible" :title="authDialogTitle" width="600px">
    <el-table :data="authListWithStatus" border max-height="400">
      <el-table-column prop="description" label="权限描述" width="200" />
      <el-table-column prop="code" label="权限代码" width="150" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.enabled" type="success">启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="选择" width="80">
        <template #default="scope">
          <el-checkbox v-model="scope.row.have"></el-checkbox>
        </template>
      </el-table-column>
    </el-table>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="authDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAuth">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>


<style scoped>
#title {
  font-size: 20px;
  font-weight: 600;
  color: #e0e0e0;
}
.dialog-footer {
  text-align: right;
}
</style>